package com.gjy.sentinel.demo.example;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gjy.sentinel.annotation.SentinelOrigin;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-10-15 16:41:55
 */
@Service
public class OrderServiceImpl implements IOrderService, InitializingBean {

    @Override
    @SentinelResource(
            value = "com.gjy.sentinel.demo.example.OrderServiceImpl.createOrder",
            blockHandlerClass = OrderBlockHandler.class,
            blockHandler = "handleBlock",
            fallbackClass = OrderFallback.class,
            fallback = "fallback")
    @SentinelOrigin(resourceName = "com.gjy.sentinel.demo.example.OrderServiceImpl.createOrder",
            value = "appB")
    public String createOrder(String userId, String sku, int amount) {
        // 业务逻辑（这里随便写点东西模拟）
        if (amount <= 0) {
            throw new IllegalArgumentException("amount must > 0");
        }
        // ContextUtil.enter("com.gjy.sentinel.demo.example.OrderServiceImpl.createOrder", "appA");
        /*try {
            // 熔断降级使用
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }*/
        // 假设调用了下游库存、支付等系统……
        return "order-" + System.currentTimeMillis();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("加载规则");
        /*FlowRule rule = new FlowRule();
        rule.setResource("com.gjy.sentinel.demo.example.OrderServiceImpl.createOrder");
        rule.setCount(1);       // 5 QPS
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);       // 1 = QPS
        rule.setStrategy(RuleConstant.STRATEGY_RELATE);    // 0 = 直接限流
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
        FlowRuleManager.loadRules(Collections.singletonList(rule));*/
        ObjectMapper MAPPER = new ObjectMapper();

        /*Converter<String, List<FlowRule>> FLOW_RULE_LIST_PARSER =
                source -> {
                    try {
                        return MAPPER.readValue(source, new TypeReference<List<FlowRule>>() {
                        });
                    } catch (IOException e) {
                        // 统一包装为 RuntimeException，SentinelDataSource 只接受 RuntimeException
                        throw new RuntimeException("Parse FlowRule JSON failed", e);
                    }
                };
        String s = "D:\\code\\java\\microservice_spc\\utils-all\\sentinel-util\\src\\main\\resources\\sentinel-rules\\flow-demo.json";
        FileRefreshableDataSource<List<FlowRule>> frd = new FileRefreshableDataSource<>(s, FLOW_RULE_LIST_PARSER);
        FlowRuleManager.register2Property(frd.getProperty());*/

        /*DegradeRule rule = new DegradeRule();
        rule.setResource("com.gjy.sentinel.demo.example.OrderServiceImpl.createOrder");
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);
        rule.setCount(1);
        rule.setTimeWindow(5);*/

        /*Converter<String, List<DegradeRule>> DEGRADE_RULE_LIST_PARSER =
                source -> {
                    try {
                        return MAPPER.readValue(source, new TypeReference<List<DegradeRule>>() {
                        });
                    } catch (IOException e) {
                        // 统一包装为 RuntimeException，SentinelDataSource 只接受 RuntimeException
                        throw new RuntimeException("Parse FlowRule JSON failed", e);
                    }
                };
        String s = "D:\\code\\java\\microservice_spc\\utils-all\\sentinel-util\\src\\main\\resources\\sentinel-rules\\degrade-demo.json";
        FileRefreshableDataSource<List<DegradeRule>> frd = new FileRefreshableDataSource<>(s, DEGRADE_RULE_LIST_PARSER);
        DegradeRuleManager.register2Property(frd.getProperty());*/

        /*AuthorityRule rule = new AuthorityRule();
        rule.setStrategy(RuleConstant.AUTHORITY_WHITE);*/
        Converter<String, List<AuthorityRule>> DEGRADE_RULE_LIST_PARSER =
                source -> {
                    try {
                        return MAPPER.readValue(source, new TypeReference<List<AuthorityRule>>() {
                        });
                    } catch (IOException e) {
                        // 统一包装为 RuntimeException，SentinelDataSource 只接受 RuntimeException
                        throw new RuntimeException("Parse FlowRule JSON failed", e);
                    }
                };
        String s = "D:\\code\\java\\microservice_spc\\utils-all\\sentinel-util\\src\\main\\resources\\sentinel-rules\\authority-demo.json";
        FileRefreshableDataSource<List<AuthorityRule>> frd = new FileRefreshableDataSource<>(s, DEGRADE_RULE_LIST_PARSER);
        AuthorityRuleManager.register2Property(frd.getProperty());

    }


}
